<?php
// Copyright 2008 Datapolis Solutions OY
// 
// This file is part of a program, that is distributed
// under the terms of the GNU General Public License,
// see license.txt for details.

defined( '_JEXEC' )  or die( 'Direct Access to this location is not allowed.' );
/* voidaan includata useammastakin paikasta sama koodi... */
if ( defined( '_DPDATABASE_CLASS') ) return; 
define('_DPDATABASE_CLASS', 1 );

class DPDBInstance {
	private $dbname;
	private $prefix;
	private $host;
	private $user;
	private $pass;
	private $identifier;	
	private $database;
	
	public function __construct( $dbname, $prefix, $host, $user, $pass ) {
		$this->dbname = $dbname;
		$this->prefix = $prefix;
		$this->host = $host;
		$this->user = $user;
		$this->pass = $pass;
		$this->identifier = $user.$pass.$host.$dbname.$prefix;
		$this->created = false;
	}
	public function getIdentifier() {
		return $this->identifier;
	}
		
	public function getDatabaseInstance() {
		if ( !($this->database instanceof database)  ) {
			$this->database =& new database( $this->host, $this->user, $this->pass, $this->dbname, $this->prefix );
		}
		return $this->database;		
	}
}

class DPDatabase {
	private static $instances;	
	
	public static function getInstance( $dbname, $prefix='jos_', $host=null, $user=null, $pass=null ) {
		global $mosConfig_host, $mosConfig_user, $mosConfig_password, $mosConfig_db, $mosConfig_dbprefix, $database;		
		
		if ( is_null( $host ) ) $host = $mosConfig_host;
		if ( is_null( $user ) ) $user = $mosConfig_user;
		if ( is_null( $pass ) ) $pass = $mosConfig_password;
		
		if ( $dbname == $mosConfig_db && 
			 $prefix == $mosConfig_dbprefix && 
			 $host   == $mosConfig_host &&
			 $user   == $mosConfig_user && 
			 $pass   == $mosConfig_password ) {
			return $database;
		}
				
		
		$dpdb =& new DPDBInstance( $dbname, $prefix, $host, $user, $pass );
		$id = $dpdb->getIdentifier();
	
		if ( !is_array( self::$instances ) ) {
			self::$instances = array();
		}
		if ( !isset( self::$instances[ $dpdb->getIdentifier() ] ) ) {			
			self::$instances[ $dpdb->getIdentifier() ] =& $dpdb;
		} else {
			$dpdb =& self::$instances[ $dpdb->getIdentifier() ];
		}
		
		return $dpdb->getDatabaseInstance();
	}	
}

?>